<?php
namespace Home\Controller;
use Think\Controller;
use Common\Controller\WapController;

class OrderController extends WapController {

    static $status = array(
        "待支付", "施工中", "待评价", "已完成"
    );

    public function index(){

        $where = array();
        if(I("request.status")!='全部'){
            $where['state'] = I("request.status");
        }

        $order = M("reziti_order")->where($where)->select();
        //print_r($order);

        $this->display();
    }

    public function detail(){
        $orderId = I("request.orderId");
        $where = array("o.name"=>$orderId);
        $order = M("reziti_order o")->field("o.*, l.name as lname, l.phone as lphone, l.addr, l.addr2")
                    ->where($where)
                    ->join(C("DB_PREFIX")."reziti_linkman l on l.id = o.linkman_id", "LEFT")
                    ->find();
        if(!$order){
            $this->error("订单没有找到");
        }
        $this->assign("order", $order);
        $this->display();
    }

    public function pay(){
        $orderId = I("request.orderId");
        if(!$orderId){
            $this->error("缺少必要的参数");
        }

        $where = array("name"=>$orderId);
        $order = M("reziti_order")->where($where)->find();
        $this->assign("order", $order);
        $this->display();
    }

    public function paySuccess() {
        // 修改订单状态
        $orderId = I("get.orderId");
        $order = M("reziti_order")->where(array("name"=>$orderId))->find();
        if (!$order){
            $this->assign("errMsg", "没有找到该订单");
            $this->display ("error");
            exit;
        }

        // 更新数据
        $data = array(
            "state" => '施工中', //1表示支付成功
            "date_pay" => date("Y-m-d H:i:s"),
            "uuser" => session("token"),
            "utime" => time(),
        );
        $payMsg = "订单支付成功";
        $res = M("reziti_order")->where(array("name"=>$orderId))->save($data);
        if (!$res){ //如果更新订单状态失败，则报错并写入日志中
            $payMsg = "订单异常，请联系管理员";
        }

        $member = M("reziti_member")->where(array("phone"=>$order['wechat_phone']))->find();
        if(!$member){
            $this->error("操作失败，会员信息不存在");
        }

        //推送支付成功的消息
        $data = array(
            "first" => array("value"=>"订单支付成功"),
            "keyword1" => array("value"=>$order['wechat_name']),
            "keyword2" => array("value"=>$order['item']),
            "keyword3" => array("value"=>$order['total']),
            "keyword4" => array("value"=>$order["date_pay"]),
            "remark" => array("value"=>"支付成功，我们将尽快安排师傅上门服务"),
        );
        $res = $this->message_template_send($data, $member['token']);
        if($res){
            file_put_contents(PUBLIC_PATH."a.txt", "xxxx-".serialize($res), FILE_APPEND);
            \Think\Log::write("服务进度通知 推送成功".serialize($res));
        }else{
            file_put_contents(PUBLIC_PATH."a.txt", "yyyyy-".serialize($res), FILE_APPEND);
            \Think\Log::write("服务进度通知 推送失败".serialize($res));
        }

        $this->assign('payMsg', $payMsg);
        $this->assign('order', $order);
        $this->display ("paySuccess");
    }

    /**
     * 发送模版消息
     */
    public function message_template_send($msg, $openid){
        $data = array(
            "touser"=> $openid,
            "template_id"=> "Zxe2Hw6gtsD03W0ROSHfV-My2mHtM4ojjB-Mb9HpjBk",
            "url" => "",
            "topcolor" => '#aace3b',
            "data" => $msg,
        );
        vendor('WxPayPubHelper.WxPayPubHelper');
        $jsApi = new \wxPay\WxPayPubHelper\JsApi_pub();
        return $jsApi->message_template_send($data);
    }

    public function payCancel() {
        $this->assign('showRepayBtn', false);
        $this->assign('errMsg', "订单已取消");
        $this->assign('orderId', I('get.orderId'));
        $this->display ("payFailed");
    }

    public function payFailed() {
        $this->assign('showRepayBtn', true);
        $this->assign('errMsg', "订单支付失败");
        $this->assign('orderId', I('get.orderId'));
        $this->display ("payFailed");
    }

    /**
     * abort
     */
    public function getJsApiSignature()
    {
        /*//配置wx.config
        session("signature", null);
        if(session("signature")){
            $this->ajaxReturn(session("signature"));
        }*/
        vendor('WxPayPubHelper.WxPayPubHelper');
        $jsApi = new \wxPay\WxPayPubHelper\JsApi_pub();
        $url = 'http://jx.renziti.cn/home/order/place.html?id=2';
        //$url = urldecode(I("post.url"));
        $signature = $jsApi->getsignature($url);
        session("signature", $signature);
        $this->ajaxReturn($signature);
    }

    public function place(){

        /*//手机验证以后才能下单*/
        if(!session("member")){
            $this->redirect("/home/me/phone");
        }

        //配置wx.config
        $url = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"];
        //session("signature", null);
        if(session("signature$url")){
            $signature = session("signature$url");
        }else{
            vendor('WxPayPubHelper.WxPayPubHelper');
            $jsApi = new \wxPay\WxPayPubHelper\JsApi_pub();
            $signature = $jsApi->getsignature($url);
            session("signature$url", $signature);
        }
        $this->assign("weconfig", $signature);

        $category = M("reziti_category")->where(array("id"=>I("get.id")))->find();
        if(!$category){
            $this->redirect("/home/index");
        }

        $this->assign("category", $category);
        $item = M("reziti_item")->where(array("category_id"=>I("get.id")))->order("seq asc")->select();
        $this->assign("item", $item);
        $this->display();
    }

    public function ajax_UploadPic(){
        //第一步：创建目录
        $member = session("member");
        $dir = PUBLIC_PATH.$member['phone'];
        if (!file_exists($dir)){
            mkdir($dir, 0777, true);
        }

        //第二步：获取media
        $media_id = I('post.media_id');
        vendor('WxPayPubHelper.WxPayPubHelper');
        $jsApi = new \wxPay\WxPayPubHelper\JsApi_pub();
        $media = $jsApi->getMedia($media_id);

        //第三步存储media
        $extension = 'jpg';
        $file_name = uniqid().'.'.$extension;
        file_put_contents($dir."/".$file_name, $media);

        //默认存储在/public目录下面，目录名为会员手机号
        $this->success($member['phone']."/".$file_name);
    }

    public function ajax_getFaults(){
        $item_id = I("post.item_id");
        $faults = M("reziti_fault")->where(array("item_id"=>$item_id))->select();
        $this->ajaxReturn($faults);
    }

    public function ajax_SubmitOrder(){
        // 第一步：生成订单号
        $orderId = $this->fn_GenerateOrderId(date("Ymd"));
        if (!$orderId){
            $this->error("订单号生成失败");
        }

        // 第二步：格式化订单信息
        $params = I("post.order");
        $order = $this->fn_PrepareOrderInfo($params, $orderId);
        $images = explode("|", $params['images']);
        for($i=0; $i<count($images); $i++){
            if($i<4){ //将上传图片的路径写入数据库中
                $order["pic".($i+1)] = $images[$i];
            }
        }

        $linkman = M("reziti_linkman")->where(array("id"=>$order['linkman_id']))->find();
        if(!$linkman){
            $this->error("订单创建失败，联系人信息缺失");
        }else{
            $order['linkman_name'] = $linkman['name'];
            $order['linkman_phone'] = $linkman['phone'];
            $order['linkman_addr'] = $linkman['addr'];
            $order['linkman_addr2'] = $linkman['addr2'];
        }

        // 第三步：接收POST过来的相关信息，并做验证
        $res = M("reziti_order")->add($order);
        if (!$res){
            $this->error("订单创建失败，请重新提交");
        }

        //返回生成后的订单ID
        $this->success($orderId);
    }

    public function ajax_GetOrderWithStatus(){
        $where = array('token'=>session("token"));
        if(I("request.status")!='全部'){
            $where['state'] = I("request.status");
        }
        $orders = M("reziti_order")->where($where)->select();
        $this->success($orders);
    }

    /**
     * 20170416 + 100001  (100001为订单总数，autoincresement=100000)
     */
    public function fn_GenerateOrderId($date){
        $orderId = "";
        $index = M("reziti_order_num")->add(array('date'=>$date));
        if($index){
            $orderId = "$date$index";
        }
        return $orderId;
    }

    public function fn_PrepareOrderInfo($params, $orderId){
        $member = session("member");
        return array(
            "state" => '待支付',
            "name" => $orderId,
            "wechat_name" => $member['name'],
            "wechat_phone" => $member['phone'],
            "token" => session("token"),
            "date_order" => date("Y/m/d"),
            "cuser" => session("token"),
            "ctime" => time(),
            "category" => $params['category'],
            "item" => $params['item'],
            "linkman_id" => $params['linkman_id'],
            "total" => $params['total'],
            "date_service" => $params['date_service'],
            "remarks" => $params['remarks'],
        );
    }

    /**
     * 获取微信支付的 PrepayId
     */
    public function fn_GetJsApiParameters($body, $out_trade_no, $total_fee){
        vendor('WxPayPubHelper.WxPayPubHelper');
        $jsApi = new \wxPay\WxPayPubHelper\JsApi_pub();
        $openid = $jsApi->openid = session('token');

        //使用统一支付接口
        $unifiedOrder = new \wxPay\WxPayPubHelper\UnifiedOrder_pub();
        $unifiedOrder->setParameter("openid","$openid");//商品描述
        $unifiedOrder->setParameter("body","$body");//商品描述
        //自定义订单号，此处仅作举例
        // $timeStamp = time();
        // $out_trade_no = WxPayConf_pub::APPID."$timeStamp";
        $unifiedOrder->setParameter("out_trade_no","$out_trade_no");//商户订单号
        //$unifiedOrder->setParameter("total_fee","$total_fee");//总金额
        $unifiedOrder->setParameter("total_fee", 1);//总金额
        $unifiedOrder->setParameter("notify_url",\wxPay\WxPayPubHelper\WxPayConf_pub::NOTIFY_URL);//通知地址
        $unifiedOrder->setParameter("trade_type","JSAPI");//交易类型

        $prepay_id = $unifiedOrder->getPrepayId();
        //=========步骤3：使用jsapi调起支付============
        $jsApi->setPrepayId($prepay_id);

        return $jsApi->getParameters();
    }

    public function ajax_doPay(){

        // 第一步：查找订单信息
        $orderId = I("post.orderId");
        $order = M("reziti_order")->where(array("name"=>$orderId))->find();
        if (!$order){
            $this->error("缺少必要参数");
        }

        // 第二步：生成PrepayId
        $totalFee = intval($order['total']*100);
        $jsApiParameters = $this->fn_GetJsApiParameters($order['item']."维修费用", $orderId, $totalFee);
        if (!$jsApiParameters){
            $this->error("订单支付处理失败，请重新支付");
        }

        // 第三步：返回结果
        $this->success(
            array(
                "orderId" => $orderId,
                'totalFee' => $order['total'],
                'jsApiParameters' => $jsApiParameters
            )
        );
    }
}